// 文章相关的action

import { ArticleDetailResponse } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import { http } from '@/utils/http'
import dayjs from 'dayjs'
// 导入本地化格式插件
import localizedFormat from 'dayjs/plugin/localizedFormat'
dayjs.extend(localizedFormat)

export const getArticleById = (id: string): RootThunkAction => {
  return async (dispatch) => {
    // 获取文章详情
    const res = await http.get<ArticleDetailResponse>(`articles/${id}`)
    console.log('文章详情res', res.data.data)
    dispatch({
      type: 'article/getArticleById',
      payload: {
        ...res.data.data,
        pubdate: dayjs(res.data.data.pubdate).locale('zh-cn').format('LL'),
      },
    })
  }
}

export const followAuthor = (
  id: string,
  isFollowed: boolean
): RootThunkAction => {
  return async (dispatch) => {
    if (isFollowed) {
      // 取关
      await http.delete(`/user/followings/${id}`)
    } else {
      // 关注
      const res = await http.post('/user/followings', {
        target: id,
      })
      console.log(res)
    }
    // 把数据更新到redux中
    dispatch({
      type: 'article/updateInfo',
      payload: {
        name: 'is_followed',
        value: !isFollowed,
      },
    })
  }
}
